//index.js
//获取应用实例
const app = getApp();
const http = require('../../utils/http');
// const order = ['red', 'yellow', 'blue', 'green', 'red'];
const util = require('util.js')
const common = require('../../utils/common')
const timeUtil = require('../../utils/util.js');

// 倒计时
function countdown(that) {
    var EndTime = new Date(that.data.endTime).getTime() || [];
    // console.log(EndTime);
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];   //单位毫秒
    // console.log(total_micro_second);
    if (total_micro_second < 0) {
        // console.log('时间初始化小于0，活动已结束状态');
        // total_micro_second = 1;     //单位毫秒 ------  WHY？
    }
    // console.log('剩余时间：' + total_micro_second);
    // 渲染倒计时时钟
    that.setData({
        clock: dateformat(total_micro_second)   //若已结束，此处输出'0天0小时0分钟0秒'
    });
    if (total_micro_second <= 0) {
        that.setData({
            clock: "已经截止"
        });
        return;
    }
    setTimeout(function () {
        total_micro_second -= 1000;
        countdown(that);
    }, 1000)
}


// 时间格式化输出，如11天03小时25分钟19秒  每1s都会调用一次
function dateformat(micro_second) {
    // 总秒数
    var second = Math.floor(micro_second / 1000);
    // 天数
    var day = Math.floor(second / 3600 / 24);
    // 小时
    var hr = Math.floor(second / 3600 % 24);
    // 分钟
    var min = Math.floor(second / 60 % 60);
    // 秒
    var sec = Math.floor(second % 60);
    return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}

Page({
    data: {
        mobile: '',
        homeAt: '../images/icon/homeAt.png',
        over: '../images/icon/over.png',
        my: '../images/icon/my.png',
        subjectType: '',
        goodsList: [],
        height: '',
        endTime: '2019-09-01 23:59:59',
        searchKeyword: '',  //需要搜索的字符
        searchSongList: [], //放置返回数据的数组
        isFromSearch: true,   // 用于判断searchSongList数组是不是空数组，默认true，空的数组
        searchPageNum: 1,   // 设置加载的第几次，默认是第一次
        callbackcount: 5,      //返回数据的个数
        searchLoading: false, //"上拉加载"的变量，默认false，隐藏
        searchLoadingComplete: false  //“没有数据”的变量，默认false，隐藏
    },
    //页面显示
    onShow: function () {
    },
    //页面加载
    onLoad: function (options) {

        // 判断活动是否过期
        var time = timeUtil.formatTime(new Date());
        this.setData({
            time: time
        })

        countdown(this);
        //小程序扫码
        if (options.q !== undefined) {
            const url = decodeURIComponent(options.q);
            const id = url.substring(url.lastIndexOf("/") + 1);
            wx.navigateTo({
                url: '../product/product?productId=' + id
            })
        }

        //如果带的有参数判定为分享
        if (options.productId) {
            wx.navigateTo({
                url: '../product/product?productId=' + options.productId
            })
        }


        //加载页面
        this.getCategoryList();
        this.fetchSearchList();
        this.getImgUrls();
        this.getSaleList();
        wx.getSystemInfo({
            success: (res) => {
                this.setData({
                    height: res.windowHeight
                })
            }
        })
    },


    //得到banner图
    getImgUrls: function () {
        http._get("/mini/getUploadFile").then(res => {
            if (res.code == 200) {
                this.setData({
                    'imgUrls': res.result,
                });
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none',
                    duration: 2000
                });
                setTimeout(function () {
                    wx.hideToast()
                }, 2000)
            }

        }).catch(e => {
            console.log(e)
        });
    },

// /mini/queryCouponByQuality
    //得到精品推荐
    getSaleList: function () {
        http._get('/mini/queryCouponByQuality').then(res => {
            if (res.code == 200) {
                let that = this;
                if (res.result.length > 0) {
                    that.setData({
                        saleList: res.result,
                        saleWrap: false
                    });
                } else {
                    that.setData({
                        saleWrap: true
                    });
                }

            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none',
                    duration: 2000
                });
            }
        })
    },


    //得到分类列表
    getCategoryList: function () {
        http._get("/mini/getCategory").then(res => {
            if (res.code == 200) {
                this.setData({
                    'categoryList': res.result
                });
            } else {
                wx.showToast({
                    title: res.message,
                    icon: 'none',
                    duration: 2000
                });
            }

        }).catch(e => {
            console.log(e)
        });
    },


    bindSubject: function (e) {//分类选择事件
        // console.log(e.currentTarget.dataset.index);
        this.setData({
            'subjectType': e.currentTarget.dataset.index,
            searchKeyword: e.currentTarget.dataset.index,
            isFromSearch: true,
            searchSongList: [], //放置返回数据的数组
            searchPageNum: 1,   // 设置加载的第几次，默认是第一次
            callbackcount: 5,      //返回数据的个数
            searchLoading: false, //"上拉加载"的变量，默认false，隐藏
            searchLoadingComplete: false  //“没有数据”的变量，默认false，隐藏
        });
        //拉取列表信息

        this.fetchSearchList();


    },


    //搜索，访问网络
    fetchSearchList: function () {
        let that = this;
        // categoryId
        let searchKeyword = that.data.searchKeyword,//输入框字符串作为参数
            searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数
            callbackcount = that.data.callbackcount; //返回数据的个数
        //访问网络
        util.getSearchMusic(searchKeyword, searchPageNum, callbackcount, function (data) {
            //判断是否有数据，有则取数据
            if (data.size != 0) {
                let searchList = [];
                //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
                that.data.isFromSearch ? searchList = data.list : searchList = that.data.searchSongList.concat(data.list);
                if (data.size < callbackcount) {
                    that.setData({
                        searchSongList: searchList, //获取数据数组
                        searchLoadingComplete: true, //把“没有数据”设为true，显示
                        searchLoading: false  //把"上拉加载"的变量设为false，隐藏
                    });
                } else {
                    that.setData({
                        searchSongList: searchList, //获取数据数组
                        searchLoading: true   //把"上拉加载"的变量设为false，显示
                    });
                }

            } else {
                let searchList = [];
                //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
                that.data.isFromSearch ? searchList = data.list : searchList = that.data.searchSongList.concat(data.list);
                that.setData({
                    searchSongList: searchList,
                    searchLoadingComplete: true, //把“没有数据”设为true，显示
                    searchLoading: false  //把"上拉加载"的变量设为false，隐藏
                });
            }
        })
    },

    //滚动到底部触发事件
    searchScrollLower: function () {
        let that = this;
        if (that.data.searchLoading && !that.data.searchLoadingComplete) {
            that.setData({
                searchPageNum: that.data.searchPageNum + 1,  //每次触发上拉事件，把searchPageNum+1
                isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false
            });
            that.fetchSearchList();
        }
    },

//点击搜索按钮，触发事件
    keywordSearch: function (e) {
        this.setData({
            searchPageNum: 1,   //第一次加载，设置1
            searchSongList: [],  //放置返回数据的数组,设为空
            isFromSearch: true,  //第一次加载，设置true
            searchLoading: true,  //把"上拉加载"的变量设为true，显示
            searchLoadingComplete: false //把“没有数据”设为false，隐藏
        })
        this.fetchSearchList();
    },
//跳转到商品详情
    goodsInfo: function (e) {
        const productId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '../product/product?productId=' + productId
        })
    },
    //分享
    onShareAppMessage: function () {
        return {
            title: '优惠券',
            desc: '优惠多多，实惠多多',
            path: '/pages/index/index'
        }
    },


})
